package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"new00/cache"
	"new00/models"
)

type NewController struct {
	beego.Controller
}

func (c *NewController) Add() {
	title := c.GetString("title")
	time := c.GetString("time")
	sort := c.GetString("sort")
	var new models.New
	new.Title = title
	new.Time = time
	new.Sort = sort
	err := new.Add()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}
	news, _ := new.List()
	jsonData, _ := json.Marshal(news)
	cache.Rdb.Set(cache.Ctx, "news", jsonData, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
}
func (c *NewController) List() {
	cacheData := cache.Rdb.Get(cache.Ctx, "news").Val()
	var news []*models.New
	if cacheData == "" {
		models.DB.Find(&news)
		jsonData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, "novel_list", jsonData, 0)
	} else {
		json.Unmarshal([]byte(cacheData), &news)
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "获取成功",
		"data": news,
	}
	c.ServeJSON()
	return
}
func (c *NewController) Up() {
	id, _ := c.GetInt("id")
	if id < 1 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}
	var novel models.New
	novel.ID = uint(id)
	novel.Title = c.GetString("title")
	novel.Time = c.GetString("time")
	novel.Sort = c.GetString("sort")
	err := novel.Update()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "跟新失败",
		}
		c.ServeJSON()
		return
	}

	novels, _ := novel.List()
	jsonData, _ := json.Marshal(novels)
	//跟新 redis 缓存
	cache.Rdb.Set(cache.Ctx, "novel", jsonData, 0)

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "跟新成功",
	}
	c.ServeJSON()
}
func (c *NewController) Del() {
	id, _ := c.GetInt("id")
	if id < 1 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "ID不能为0",
		}
		c.ServeJSON()
		return
	}

	var novel models.New
	novel.ID = uint(id)
	err := novel.Del()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除失败",
		}
		c.ServeJSON()
		return
	}

	novels, _ := novel.List()
	jsonData, _ := json.Marshal(novels)
	//更新 redis 缓存
	cache.Rdb.Set(cache.Ctx, "novel", jsonData, 0)

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return
}
